package com.zzy.database.controller;


import com.zzy.database.pojo.Result;
import com.zzy.database.pojo.User;
import com.zzy.database.service.UserService;
import com.zzy.database.utils.Jwtutil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @PostMapping("/register")
    public Result<String> register(@RequestBody User user) {
        System.out.println(user.getUsername());

        userService.register(user);
        return Result.success("注册成功");
    }

    @PostMapping("/login")
    public Result<String> login(@RequestBody User user) {
        String inputPassword = user.getPassword();
        String username = user.getUsername();
        System.out.println(inputPassword);

        User loginUser = userService.findUserByNameAndType(user);
        System.out.println(loginUser);
        if (loginUser == null) {
            return Result.error("用户名错误");
        } else if (inputPassword.equals(loginUser.getPassword())) {
            Map<String, Object> claims = new HashMap<>();
            claims.put("username", username);
            claims.put("userType", user.getUserType());
            claims.put("id",user.getId());
            String token = Jwtutil.genToken(claims);
            //System.out.println(token);
            return Result.success(token);
        } else {
            return Result.error("密码错误");
        }
}

    @PutMapping("/resetpassword")
    public Result resetPassword(@RequestParam String oldPassword, @RequestParam String newPassword,@RequestHeader("Authorization") String authorization) {


        Map<String, Object> map = Jwtutil.parseToken(authorization);
        String username = (String) map.get("username");
        String userType=(String) map.get("userType");
        User user=new User();
        user.setUsername(username);
        user.setUserType(userType);


        if(userService.changepasswd(user,oldPassword,newPassword)){
            // 处理密码重置
            return Result.success();
        } else{
            return Result.error("密码错误");
        }


    }


}
